package top.eggcode.component.session.manager;

import top.eggcode.component.session.Session;
import top.eggcode.component.session.SimpleSession;
import top.eggcode.component.session.exception.InvalidSessionException;
import top.eggcode.component.session.store.MemorySessionStore;
import top.eggcode.component.session.store.SessionStore;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;

/**
 * Title:
 * Description: TODO
 * Date: 2021/8/12 0:13
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public class SimpleSessionManager extends VerificationSessionManager {

    protected SessionStore sessionDAO;
    /**
     * 全局默认存活时间，单位：秒
     */
    private long globalSessionTimeout = 1800L;

    public SimpleSessionManager() {
        this.sessionDAO = new MemorySessionStore();
    }

    public void setSessionDAO(SessionStore sessionDAO) {
        this.sessionDAO = sessionDAO;
    }

    public void setGlobalSessionTimeout(long globalSessionTimeout) {
        this.globalSessionTimeout = globalSessionTimeout;
    }

    @Override
    protected Session doGetSession(Serializable sessionKey) throws InvalidSessionException {
        return sessionDAO.readSession(sessionKey);
    }

    @Override
    protected Session doCreateSession() {
        SimpleSession session = new SimpleSession();
        // 过期时间
        session.setTimeout(globalSessionTimeout);
        sessionDAO.create(session);
        return session;
    }

    @Override
    protected Collection<Session> getActiveSessions() {
        Collection<Session> active = sessionDAO.getActiveSessions();
        return active != null ? active : Collections.emptySet();
    }

    @Override
    protected void onChange(Session session) {
        sessionDAO.update(session);
    }
}
